//
//  ESAsyncTimer.m
//  SportsGather
//
//  Created by 付有芳 on 15/9/7.
//  Copyright (c) 2015年 Egymcom. All rights reserved.
//

#import "ESAsyncTimer.h"

@interface ESAsyncTimer ()

@property (nonatomic,strong) dispatch_source_t timer;

@end

@implementation ESAsyncTimer

-(instancetype)init
{
    if (self = [super init]) {
        _isRunning = NO;
        return self;
    }
    return self;
}

- (instancetype)initWithTimeInterval:(CGFloat)timeInterval{
    
    self = [super init];
    if (!self) {
        return nil;
    }
    _isRunning = NO;
    self.timeInterval = timeInterval;
    return self;
}


-(void)startTimer{
    
    if(self.timeInterval == 0.0) {
        self.timeInterval = 0.1;
    }
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    //每秒执行
    dispatch_source_set_timer(self.timer,dispatch_walltime(NULL,0), self.timeInterval * NSEC_PER_SEC, 0);    dispatch_source_set_event_handler(self.timer, ^{
        if (self.delegate && [self.delegate respondsToSelector:@selector(doUpdate:)]) {
            [self.delegate doUpdate:self];
        }
    });
    self.isRunning=YES;
    dispatch_resume(self.timer);
}

-(void)stopTimer{
    self.isRunning=NO;
    if(self.timer != NULL) {
        dispatch_source_cancel(self.timer);
    }
}


@end
